package com.symbio.service.impl;

import com.symbio.dao.UserDao;
import com.symbio.dao.impl.UserDaoImpl;
import com.symbio.domain.PageBean;
import com.symbio.domain.User;
import com.symbio.service.UserService;

import java.util.List;
import java.util.Map;

public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDaoImpl();

    @Override
    public List<User> findAll() {
        return userDao.findAll();
    }

    @Override
    public User login(User user) {
        return userDao.login(user);
    }

    @Override
    public int addUser(User user) {
        return userDao.add(user);
    }

    @Override
    public void deleteUser(String id) {
        userDao.delete(Integer.parseInt(id));
    }

    @Override
    public void updateUser(User user) {
        userDao.update(user);
    }

    @Override
    public User findUser(String id) {
        return userDao.find(Integer.parseInt(id));
    }

    @Override
    public void deleteUsers(String[] ids) {
        if (ids == null) {
            return;
        }
        for (String id : ids) {
            deleteUser(id);
        }
    }

    @Override
    public PageBean<User> findUserByPage(String _currentPage, String _rows, Map<String, String[]> parameterMap) {
        if (_currentPage == null) {
            _currentPage = "1";
        }

        if (_rows == null) {
            _rows = "5";
        }

        int rows = Integer.parseInt(_rows);
        int currentPage = Integer.parseInt(_currentPage);

        if (rows <= 0) {
            rows = 5;
        }

        if (currentPage <= 1) {
            currentPage = 1;
        }

        PageBean pageBean = new PageBean();
        pageBean.setTotalCount(userDao.findTotalCount(parameterMap));
        pageBean.setList(userDao.findByPage((currentPage - 1) * rows, rows, parameterMap));
        pageBean.setCurrentPage(currentPage);
        pageBean.setRows(rows);
        pageBean.setTotalPage(pageBean.getTotalCount()/rows + (pageBean.getTotalCount() % rows == 0 ? 0 : 1));
        return pageBean;
    }
}
